package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.impl.MinIOFileStorageService;
import com.heima.model.dtos.PageResponseResult;
import com.heima.model.dtos.ResponseResult;
import com.heima.model.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 自媒体图片处理
 * @date 2023/1/11 16:13
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinIOFileStorageService minioFileStorageService;

    /**
     * @param userId
     * @param file
     * @return com.heima.model.dtos.ResponseResult
     * @description 上传图片文件
     * @author 31115
     * @date 2023/1/11 16:17
     */
    @Override
    @Transactional
    public ResponseResult uploadPicture(Integer userId, MultipartFile file) {

        //修改文件原始名称
        String newName = updatePictureName(file.getOriginalFilename());
        if (StringUtils.isEmpty(newName)) {
            log.debug("自媒体上传图片新文件名为空：{}", newName);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //文件上传到minio
        String result = addPictureMinio(newName, file);
        if (result == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //获取数据保存到数据库
        WmMaterial wmMaterial = this.addPictureDB(userId, result);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        return ResponseResult.okResult(wmMaterial);
    }

    //修改文件原始名称
    public String updatePictureName(String ofSuffix) {

        String suffix = ofSuffix.substring(ofSuffix.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newName = uuid + suffix;
        log.debug("自媒体上传图片文件文件名称修改成功,原始文件名：{}，修改后的文件名：{}", ofSuffix, newName);
        return newName;
    }

    //获取数据保存到数据库
    @Override
    public WmMaterial addPictureDB(Integer userId, String url) {

        if (StringUtils.isEmpty(userId)) {
            log.debug("自媒体上传图片获取数据保存到数据库userid为空：{}", userId);
            return null;
        }
        if (StringUtils.isEmpty(url)) {
            log.debug("自媒体上传图片获取数据保存到数据库图片url为空：{}", url);
            return null;
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(userId);
        wmMaterial.setType((short) 0);
        wmMaterial.setUrl(url);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());

        this.save(wmMaterial);
        log.debug("自媒体上传图片获取数据保存到数据库成功");
        return wmMaterial;
    }


    //文件上传到minio
    private String addPictureMinio(String fieldName, MultipartFile file) {
        /**
         *  上传图片文件
         * @param prefix  文件前缀
         * @param filename  文件名
         * @param inputStream 文件流
         * @return 文件全路径
         */
        try {
            String url = minioFileStorageService.uploadImgFile("", fieldName, file.getInputStream());
            log.debug("自媒体上传图片文件成功，文件名称：{}", fieldName);
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            log.debug("自媒体上传图片文件出错：{}", e.getMessage());
            return null;
        }
    }


    /**
     * @param userId
     * @param dto
     * @return com.heima.model.dtos.PageResponseResult
     * @description 素材列表查询
     * @author 31115
     * @date 2023/1/11 21:18
     */
    @Override
    public PageResponseResult filedList(Integer userId, WmMaterialDto dto) {

        if (dto == null || dto.getIsCollection() == null) {
            log.debug("素材列表查询无数据传入：{}", dto);
            throw new RuntimeException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST + "");
        }
        //根据用户id查询出所有素材数据
        //判断isCollection 是否收藏

        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if ("1".equals(dto.getIsCollection().toString())) {
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        wrapper.eq(WmMaterial::getUserId,userId);

        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage pageList = page(new Page<>(dto.getPage(),dto.getSize()),wrapper);

        if (pageList == null) {
            log.debug("素材列表查询db无数据：{}", pageList);
            throw new RuntimeException(AppHttpCodeEnum.DATA_NOT_EXIST + "");
        }

        PageResponseResult pageResponseResult = new PageResponseResult();
        pageResponseResult.setData(pageList.getRecords());
        pageResponseResult.setCurrentPage(Integer.parseInt(pageList.getCurrent() + ""));
        pageResponseResult.setSize(Integer.parseInt(pageList.getSize() + ""));
        pageResponseResult.setTotal(Integer.parseInt(pageList.getTotal() + ""));

        log.debug("素材列表查询成功：{}", pageResponseResult);
        return pageResponseResult;

    }
}
